package com.erclab.xbuilder.formhelpers;

import java.util.HashMap;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.dataAccess.FormDAO;
import com.erclab.internal.xpresso.datavalidators.DataValidationError;
import com.erclab.internal.xpresso.exceptions.FormException;
import com.erclab.internal.xpresso.forms.Form;
import com.erclab.internal.xpresso.forms.FormHelper;
import com.erclab.internal.xpresso.util.FormElementUtil;
import com.erclab.xbuilder.db.MysqlDatabaseManager;
import com.erclab.xbuilder.exception.DBManagerException;

public class CreateFormHelper implements FormHelper {

	public void afterFormCreation(Form theForm) throws FormException {
		// Nada to do

	}

	public void afterModification(Form theForm, HashMap keyValues) throws FormException, DataValidationError {
		// After the object has been inserted in the Objects table
		// we need to create the table to hold the objects
		MysqlDatabaseManager mdm = new MysqlDatabaseManager();
		String title = FormElementUtil.getElementValue(theForm, keyValues, "title");
		title = title.replace(' ', '_');
		FormDAO dao = Settings.getRepository().getDaoFactory().getFormDAO();
		Form newForm = dao.createForm(title);
		
		String tableName = "f_" + newForm.getIdForm();
		try {
			mdm.createTable(tableName, null);
		} catch (DBManagerException e) {
			throw new FormException("An error occurred creating a table: " + e.getTheException());
		}
		
		
	}

	public void afterSubmission(Form theForm, HashMap keyValues)
			throws FormException, DataValidationError {
		// Nada to do

	}

	public void beforeFormCreation(Form theForm) throws FormException {
		// Nada to do

	}

}
